package com.hoaptt.model;

import com.hoaptt.helper.Coordinate;
import com.hoaptt.helper.RoundButton;
import com.hoaptt.pieces.Piece;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import javax.swing.BorderFactory;
import javax.swing.JPanel;
import javax.swing.JFrame;
import javax.swing.SwingUtilities;
import javax.swing.border.Border;

/**
 *
 * @author ThuHoa
 */
public class BoardPanel extends JPanel {

    private Board board;
    private RoundButton[][] buttons; // array of buttons to stored buttons in board
    public static final int ROW = Board.ROW;
    public static final int COL = Board.COL;
    private int dcell; // length of a cell in board
    //variables to store clicked button
    private int countEat = 0;
    private int countMove = 0;
    private Coordinate button_loc1 = null;
    private Coordinate button_loc2 = null;
    private Coordinate default_loc;
    private Coordinate buttonMove_loc;

    public int getDcell() {
        return dcell;
    }

    public void setDcell(int dcell) {
        this.dcell = dcell;
    }

    // constructor
    public BoardPanel() {
        this.setLayout(null);
        board = new Board();
        buttons = new RoundButton[ROW + 1][COL + 1];
        // get coordinate when mouse click
        this.addMouseListener(new MouseListener() {

            @Override
            public void mouseClicked(MouseEvent e) {
                int x = e.getX();
                int y = e.getY();
                Coordinate loc = checkLocation(x, y);
                default_loc = new Coordinate(loc.getRow(), loc.getCol());
                countMove++;
                processMove();// this method is swap two button at loc1 and loc2
                 setColorSelected(button_loc1);
                //testing::
                System.out.println("loc: " + loc.getRow() + "\t" + loc.getCol());
            }

            @Override
            public void mousePressed(MouseEvent e) {
            }

            @Override
            public void mouseReleased(MouseEvent e) {
            }

            @Override
            public void mouseEntered(MouseEvent e) {
            }

            @Override
            public void mouseExited(MouseEvent e) {
            }
        });
        // add button (initial location) in board
        for (int i = 0; i <= ROW; i++) {
            for (int j = 0; j <= COL; j++) {
                Coordinate loc = new Coordinate(i, j);
                RoundButton button = new RoundButton("", loc);
                buttons[i][j] = button;
                // tao mang cac button
                this.add(buttons[i][j]);
                final int a = i;
                final int b = j;

                // button is click will print coordinate in output
                buttons[i][j].addActionListener(new ActionListener() {

                    @Override
                    public void actionPerformed(ActionEvent e) {
                        RoundButton button = buttons[a][b];
                        button.setVisible(true);
                        // x, y is coordinate of button
                        int x = button.getLoc().getRow();
                        int y = button.getLoc().getCol();
                        if (countEat % 2 == 0) {
                            button_loc1 = new Coordinate(x, y);
                            // buttons[x][y].setBackground(Color.white);
                            buttonMove_loc = new Coordinate(x, y);
                        } else {
                            button_loc2 = new Coordinate(x, y);
                        }
                        System.out.println("loc: " + buttons[a][b].getLoc().getRow() + "\t" + buttons[a][b].getLoc().getCol());

                        System.out.println("CountEat: " + countEat);
                        countEat++;
                        processEat(); // this method to swap to piece
                        setColorSelected(button_loc1);
                        System.out.println("CountMove: " + countMove);
                    }
                });
            }
        }
    }
// end constructor

    private void setColorSelected(Coordinate button_loc1) {
      
        for (int i=0; i<=8; i++){
            for (int j=0; j<=9;j++){
                buttons[i][j].setBackground(null);
            }
        }
        buttons[button_loc1.getRow()][button_loc1.getCol()].setBackground(Color.white);
    }

    @Override
    public void paint(Graphics g) {
        super.paint(g);
        // show or hide button on panel
        for (int i = 0; i <= board.ROW; i++) {
            for (int j = 0; j <= board.COL; j++) {
                buttons[i][j].setOpaque(true);
                if (board.getPiece(i, j).getName().equals("default")) {
                    buttons[i][j].setVisible(false);
                } else {
                    buttons[i][j].setVisible(true);
                }
            }
        }
        g.setColor(Color.BLUE);
        // get height and width to compare
        int dmin = getHeight() > getWidth() ? getWidth() : getHeight();
        dcell = dmin / 11;
        int h = (dmin / 11) * 9;
        int w = dmin / 11 * 8;

        // ve duong doc
        for (int i = 0; i < 9; i++) {
            g.drawLine(dcell * i + dcell, 0 + dcell, dcell * i + dcell, h + dcell);
        }
        // ve duong ngang
        for (int i = 0; i < 10; i++) {
            g.drawLine(dcell, dcell * i + dcell, w + dcell, dcell * i + dcell);
        }
        // ve duong cheo
        g.drawLine(dcell * 4, dcell, dcell * 6, dcell * 3);
        g.drawLine(dcell * 6, dcell, dcell * 4, dcell * 3);
        g.drawLine(dcell * 4, h + dcell, dcell * 6, dcell * 8);
        g.drawLine(dcell * 6, h + dcell, dcell * 4, dcell * 8);

        // ve song
        Color c = this.getBackground();
        g.setColor(c);
        g.fillRect(dcell + 1, dcell * 5 + 1, w - 1, dcell - 1);

        //danh dau quan co
        move(g, h, w, dcell);

        // show initial state of board
        for (int i = 0; i <= ROW; i++) {
            for (int j = 0; j <= COL; j++) {
                buttons[i][j].setLayout(null);
                buttons[i][j].setBounds(dcell * i + dcell / 2 + 5, dcell * j + dcell / 2 + 5, 5 * (dcell / 6), 5 * (dcell / 6));
                Border emptyBorder = BorderFactory.createEmptyBorder();
                buttons[i][j].setBorder(emptyBorder);
                buttons[i][j].setOpaque(true);
                this.setLayout(null);
//                }
            }
        }

        // show color of piece
        // player A: clolor red
        // player B: clolor blue
        for (int i = 0; i <= board.ROW; i++) {
            for (int j = 0; j <= board.COL; j++) {
                if (board.getPiece(i, j).getPlayer().equals(Piece.PLAYER.A)) {
                    buttons[i][j].setForeground(Color.red);
                } else {
                    buttons[i][j].setForeground(Color.blue);
                }
            }
        }

        // resize text of button
        for (int i = 0; i <= ROW; i++) {
            for (int j = 0; j <= COL; j++) {
                Piece piece = board.getPiece(i, j);
                buttons[i][j].setText(piece.getName());
                // ( test of button can resize (fixing)
//                Font buttonFont = buttons[i][j].getFont();
//                String buttonText = buttons[i][j].getText();
//
//                int stringWidth = buttons[i][j].getFontMetrics(buttonFont).stringWidth(buttonText);
//                int componentWidth = buttons[i][j].getWidth();
//                // Find out how much the font can grow in width.
//                double widthRatio = (double) componentWidth / (double) stringWidth;
//
//                int newFontSize = (int) (buttonFont.getSize() * widthRatio);
//                int componentHeight = buttons[i][j].getHeight();
//                // Pick a new font size so it will not be larger than the height of label.
//                int fontSizeToUse = Math.min(newFontSize, componentHeight);
//                System.out.println("text: " + buttons[i][j].getText());
//                System.out.println("font name: " + buttonFont.getFontName());
//                System.out.println("font: " + stringWidth);
//                System.out.println("componentWidth: " + componentWidth);
//                System.out.println("componentHeight: " + componentHeight);
//                // Set the label's font size to the newly determined size.
//                 buttons[i][j].getText().setFont(new Font(buttonFont.getName(), Font.PLAIN, fontSizeToUse));

                buttons[i][j].setFont(new Font("sansserif", Font.BOLD, 25));
            }
        }




    }

    public void processEat() {
        //// user has clicked two times
        ////
        //
        if (countEat == 2) {
            // neu nguoi choi chon 2 quan co cung mau lien tiep
            if (board.getAtLoc(button_loc1.getRow(), button_loc1.getCol()).getPlayer() == board.getAtLoc(button_loc2.getRow(), button_loc2.getCol()).getPlayer()) {
                button_loc1 = button_loc2; // lay vi tri cua button thu 2 thay cho button 1
                buttonMove_loc = button_loc2; //  lay vi tri cua buton 2 thay co button move
                button_loc2 = null;
                countEat--;
            } else {
                if (button_loc1 != null && button_loc2 != null) {
                    board.move(button_loc1.getRow(), button_loc1.getCol(), button_loc2.getRow(), button_loc2.getCol());
                    button_loc1 = null;
                    button_loc2 = null;
                    buttonMove_loc = null;
                    countEat = 0;
                }
                // re-paint board after swap or move
                JFrame f = (JFrame) SwingUtilities.getRoot(this);
                System.out.println(f.getName());
                f.repaint();
                this.repaint();
            }
        }
    }

    public void processMove() {
        if (countMove != 1 || buttonMove_loc == null) {
            button_loc1 = null;
            countMove = 0;
            buttonMove_loc = null;
            countEat = 0;
        }
        if (countMove == 1 && buttonMove_loc != null) {
            if (buttonMove_loc != null && default_loc != null) {
                board.move(buttonMove_loc, default_loc);
                buttonMove_loc = null;
                button_loc1 = null;
                default_loc = null;
                countMove = 0;
                countEat = 0;
                Color c = this.getBackground();
                // buttons[buttonMove_loc.getRow()][buttonMove_loc.getCol()].setBackground(Color.RED);
                // re-paint board after swap or move
                JFrame f = (JFrame) SwingUtilities.getRoot(this);
                System.out.println(f.getName());
                f.repaint();
                this.repaint();
                this.getFocusListeners();
            }

        }
    }

    private Coordinate checkLocation(int x, int y) {
        int row = (x - dcell / 2) / dcell;
        int col = (y - dcell / 2) / dcell;
        if (row <= 8 && col <= 9) {
            Coordinate loc = new Coordinate(row, col);
            return loc;
        }
        return null;
    }

    private void move(Graphics g, int h, int w, int dcell) {

        // index            0  1  2  3   4  5  6  7  8  9  10 11 12 13
        int X[] = new int[]{0, 6, -1, 1, 3, 5, 7, 0, 6, -1, 1, 3, 5, 7};
        int Y[] = new int[]{0, 0, +1, 1, 1, 1, 1, 5, 5, +4, 4, 4, 4, 4};

        int xmove;
        int ymove;
        int dmin = dcell / 9; // khoang cach tu duong danh dau den duong thang ban co

        for (int i = 0; i < X.length; i++) {
            xmove = dcell * X[i];
            ymove = dcell * Y[i];

            if (i != 2 && i != 9) {
                g.drawLine((dcell / 3) * 2 + xmove + dcell, dcell * 2 - dmin + ymove + dcell,
                        dcell - dmin + xmove + dcell, dcell * 2 - dmin + ymove + dcell);
                g.drawLine(dcell - dmin + xmove + dcell, dcell * 2 - dmin + ymove + dcell,
                        dcell - dmin + xmove + dcell, (dcell / 3) * 2 + dcell + ymove + dcell);
                //
                g.drawLine((dcell / 3) * 2 + xmove + dcell, dcell * 2 + dmin + ymove + dcell,
                        dcell - dmin + xmove + dcell, dcell * 2 + dmin + ymove + dcell);
                g.drawLine(dcell - dmin + xmove + dcell, dcell * 2 + dmin + ymove + dcell,
                        dcell - dmin + xmove + dcell, (dcell / 3) + 2 * dcell + ymove + dcell);
            }
            if (i != 6 && i != 13) {
                //
                g.drawLine((dcell / 3) * 4 + xmove + dcell, dcell * 2 + dmin + ymove + dcell,
                        dcell + dmin + xmove + dcell, dcell * 2 + dmin + ymove + dcell);
                g.drawLine(dcell + dmin + xmove + dcell, dcell * 2 + dmin + ymove + dcell,
                        dcell + dmin + xmove + dcell, (dcell / 3) + 2 * dcell + ymove + dcell);
                //
                g.drawLine((dcell / 3) * 4 + xmove + dcell, dcell * 2 - dmin + ymove + dcell,
                        dcell + dmin + xmove + dcell, dcell * 2 - dmin + ymove + dcell);
                g.drawLine(dcell + dmin + xmove + dcell, dcell * 2 - dmin + ymove + dcell,
                        dcell + dmin + xmove + dcell, (dcell / 3) * 2 + dcell + ymove + dcell);
            }
        }
    }

    @Override
    protected void paintComponent(Graphics g) {
        super.paintComponent(g);

    }

    public static void main(String[] args) {
        BoardPanel panel = new BoardPanel();
        JFrame frame = new JFrame("China chess");
        frame.setVisible(true);
        frame.add(panel, BorderLayout.CENTER);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setSize(700, 700);

    }
}
